package com.stylefeng.guns.modular.system.task;

import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.common.constant.state.GpType;
import com.stylefeng.guns.core.util.HttpClientUtil;
import com.stylefeng.guns.modular.system.constants.ImportContants;
import com.stylefeng.guns.modular.system.model.Gdhs;
import com.stylefeng.guns.modular.system.model.Gdprice;
import com.stylefeng.guns.modular.system.model.Gdtj;
import com.stylefeng.guns.modular.system.model.Gpdata;
import com.stylefeng.guns.modular.system.model.GupiaoData;
import com.stylefeng.guns.modular.system.model.Sm;
import com.stylefeng.guns.modular.system.service.IGdhsService;
import com.stylefeng.guns.modular.system.service.IGdpriceService;
import com.stylefeng.guns.modular.system.service.IGdtjService;
import com.stylefeng.guns.modular.system.service.IGpdataService;
import com.stylefeng.guns.modular.system.service.ISmService;

@Service
public class GpImportTask implements InitializingBean {

	private Logger log = LoggerFactory.getLogger(GpImportTask.class);
	
	private static final HttpClientUtil clientUtil = new HttpClientUtil();
	
	private static Map<String,Double> smMaps = new HashMap<String,Double>();

	@Autowired
	private IGpdataService iGpdataService;

	@Autowired
	private IGdtjService iGdtjService;

	@Autowired
	private IGdpriceService iGdpriceService;
	
	@Autowired
	private IGdhsService iGdhsService;
	
	@Autowired
	private ISmService iSmService;
	

	@Override
	public void afterPropertiesSet() throws Exception {
		List<Sm> smList = iSmService.selectList(null);
		for(Sm sm : smList){
			smMaps.put(sm.getgName(), sm.getgHbl());
		}
	}

	public void execute(boolean isHoliday,GpType type) {
		String url = ImportContants.getFormatAuthorityGroupPathStr(type, 1);
		HttpGet httpGet = HttpClientUtil.getGetRequest();
		try {
			httpGet.setURI(new URL(url).toURI());
			String json = clientUtil.executeAndGetWithFailedRetry(httpGet, 6,10001);
			JSONObject jsonObj = JSON.parseObject(json);
			if (jsonObj.getBooleanValue("success")) {
				int pages = jsonObj.getIntValue("pages");
				parseData(jsonObj.getString("data"), type, isHoliday);
				for(int i= 2; i <=pages ; i++){
					url = ImportContants.getFormatAuthorityGroupPathStr(type, i);
					httpGet.setURI(new URL(url).toURI());
					json = clientUtil.executeAndGetWithFailedRetry(httpGet, 6,10001);
					jsonObj = JSON.parseObject(json);
					if (jsonObj.getBooleanValue("success")) {
						parseData(jsonObj.getString("data"), type,isHoliday);
					}
				}
			}
		} catch (Exception e) {
			log.error("get gupiao data is error!" + e);
		}finally{
			httpGet.abort();
		}
	}

	private void parseData(String json, GpType type,boolean isHoliday) {
		List<GupiaoData> channelItemList = JSON.parseArray(json,GupiaoData.class);
		for (GupiaoData gupiaoData : channelItemList) {
			Wrapper<Gpdata> gpdataw = new EntityWrapper<>();
			gpdataw.eq("g_dm", gupiaoData.getSecurityCode());
			Gpdata gpdata = iGpdataService.selectOne(gpdataw);
			if(gpdata == null){
				gpdata = new Gpdata();
				gpdata.setgType(type.getCode());
				gpdata.setgDm(gupiaoData.getSecurityCode());
				gpdata.setgName(gupiaoData.getSecurityName());
				statisticsDm(gpdata);
				iGpdataService.insert(gpdata);
			}else{
				statisticsDm(gpdata);
				iGpdataService.updateById(gpdata);
			}
			Gdhs gdhs = new Gdhs();
			gdhs.setgDm(gupiaoData.getSecurityCode());
			gdhs.setgTime(gupiaoData.getEndDate());
			gdhs = iGdhsService.getGdhsByDate(gdhs);
			if(gdhs == null){
				gdhs = new Gdhs();
				gdhs.setgDm(gupiaoData.getSecurityCode());
				gdhs.setgTime(gupiaoData.getEndDate());
				gdhs.setgDm(gupiaoData.getSecurityCode());
				gdhs.setgTime(gupiaoData.getEndDate());
				gdhs.setgTimePre(gupiaoData.getPreviousEndDate());
				gdhs.setgGdbcHs(gupiaoData.getHolderNum());
				gdhs.setgGdscHs(gupiaoData.getPreviousHolderNum());
				gdhs.setgZj(gupiaoData.getHolderNumChange());
				gdhs.setgZsz(gupiaoData.getTotalCapitalisation());
				gdhs.setgZjbl(gupiaoData.getHolderNumChangeRate());
				gdhs.setgLtsz(gupiaoData.getCapitalStock());
				iGdhsService.insert(gdhs);
			}else{
				gdhs.setgDm(gupiaoData.getSecurityCode());
				gdhs.setgTime(gupiaoData.getEndDate());
				gdhs.setgDm(gupiaoData.getSecurityCode());
				gdhs.setgTime(gupiaoData.getEndDate());
				gdhs.setgTimePre(gupiaoData.getPreviousEndDate());
				gdhs.setgGdbcHs(gupiaoData.getHolderNum());
				gdhs.setgGdscHs(gupiaoData.getPreviousHolderNum());
				gdhs.setgZj(gupiaoData.getHolderNumChange());
				gdhs.setgZsz(gupiaoData.getTotalCapitalisation());
				gdhs.setgZjbl(gupiaoData.getHolderNumChangeRate());
				gdhs.setgLtsz(gupiaoData.getCapitalStock());
				iGdhsService.updateById(gdhs);
			}
			
			/**
			 * 去除节假日
			 */
			if(isHoliday){
				Gdprice gdprice = new Gdprice();
				gdprice.setgDm(gupiaoData.getSecurityCode());
				gdprice.setgTime(new Date());
				gdprice = iGdpriceService.getGdpriceByDate(gdprice);
				if(gdprice == null){
					gdprice = new Gdprice();
					gdprice.setgDm(gupiaoData.getSecurityCode());
					gdprice.setgZhs(getZbs(gupiaoData.getSecurityCode()));
					gdprice.setgTime(new Date());
					gdprice.setgPrice(gupiaoData.getLatestPrice());
					gdprice.setgZdf(gupiaoData.getPriceChangeRate());
					gdprice.setgJqZdf(gupiaoData.getRangeChangeRate());
					iGdpriceService.insert(gdprice);
				}else{
					gdprice.setgPrice(gupiaoData.getLatestPrice());
					gdprice.setgZhs(getZbs(gupiaoData.getSecurityCode()));
					gdprice.setgZdf(gupiaoData.getPriceChangeRate());
					gdprice.setgJqZdf(gupiaoData.getRangeChangeRate());
					iGdpriceService.updateById(gdprice);
				}
			}
		}
	}
	
	private double getZbs(String code){
		if(StringUtils.startsWith(code, "6")){
			code = code.concat("1");
		}else{
			code = code.concat("2");
		}
		String url = ImportContants.getPricePathStr(code);
		HttpGet httpGet = HttpClientUtil.getGetRequest();
		try {
			httpGet.setURI(new URL(url).toURI());
			String json = clientUtil.executeAndGetWithFailedRetry(httpGet, 6,10001);
			JSONObject jsonObj = JSON.parseObject(StringUtils.replace(StringUtils.replace(json, "(",""), ")", ""));
			if(jsonObj.getString("info") != null){
				return jsonObj.getJSONObject("info").getDouble("v");
			}
			return 0;
		} catch (Exception e) {
			log.error("get gupiao data is error!" + e);
			return 0;
		}finally{
			httpGet.abort();
		}
	}

	private void statisticsDm(Gpdata gpdata) {
		Gdtj s = iGdtjService.selectDateByDm(gpdata.getgDm());
		if(s == null) return;
		Gdtj newgdtj = new Gdtj();
		newgdtj.setgDm(gpdata.getgDm());
		newgdtj.setgRdate(s.getgRdate());
		newgdtj.setgSharestype("A股");
		List<Gdtj> gdtjs = iGdtjService.selectListByDate(newgdtj);
		statisticsSM(gpdata,gdtjs);
		statisticsQfill(gpdata,gdtjs);
		statisticsJJ(gpdata,gdtjs);
		statisticsGJD(gpdata,gdtjs);
		statisticsQYNJ(gpdata,gdtjs);
	}
	
	private void statisticsQYNJ(Gpdata gpdata, List<Gdtj> gdtjs) {
		int count = 0;
		for(Gdtj gdtj : gdtjs){
			if(StringUtils.contains(gdtj.getgSharehdname(), "企业年金")){
				count ++;
			}
		}
		gpdata.setgIsQynjNum(count);
	}

	private void statisticsSM(Gpdata gpdata,List<Gdtj> gdtjs){
		int grcount = 0;
		int ygcount = 0;
		for(Gdtj gdtj : gdtjs){
			if(StringUtils.contains(gdtj.getgSharehdname(), "有限合伙")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "私募")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "淡水泉")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "高毅")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "凯丰")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "信托")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "资产管理计划")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "擎天柱")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "中英益利资管")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "景林")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "丰岭")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "中欧瑞博")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "望正")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "世诚")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "泰旸")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "趣时")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "清和泉")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "弘尚")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "和聚")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "相聚")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "星石")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "重阳")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "朱雀")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "元葵")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "从容")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "富善")){
				ygcount ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "思勰")){
				ygcount ++;
			}
			
			if(smMaps.containsKey(gdtj.getgSharehdname())){
				grcount ++;
			}
			
		}
		gpdata.setgIsYgsmNum(ygcount);
		gpdata.setgIsGrsmNum(grcount);
	}
	
	private void statisticsQfill(Gpdata gpdata,List<Gdtj> gdtjs){
		int count = 0;
		for(Gdtj gdtj : gdtjs){
			if(isEnglish(gdtj.getgSharehdname())){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "法国")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "澳大利亚")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "香港中央")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "挪威中央银行")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "QFII")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "哥伦比亚")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "澳洲")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "阿布达比")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "普林斯顿")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "加拿大")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "斯坦福")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "科威特")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "中国国际金融")){
				count ++;
			}
		}
		gpdata.setgIsQfillNum(count);
	}
	
	private static boolean isEnglish(String charaString){
	   return charaString.matches("^[a-zA-Z]*");
	}
	
	private void statisticsJJ(Gpdata gpdata,List<Gdtj> gdtjs){
		int count = 0;
		for(Gdtj gdtj : gdtjs){
			if(StringUtils.contains(gdtj.getgSharehdname(), "社保")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "混合型证券投资基金")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "股票型证券投资基金")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "债券型证券投资基金")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "收益型证券投资基金")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "社会保障基金")){
				count ++;
			}
		}
		gpdata.setgIsJjNum(count);
	}
	
	private void statisticsGJD(Gpdata gpdata,List<Gdtj> gdtjs){
		int count = 0;
		for(Gdtj gdtj : gdtjs){
			if(StringUtils.contains(gdtj.getgSharehdname(), "中央汇金")){
				count ++;
			}else if(StringUtils.contains(gdtj.getgSharehdname(), "中国证券")){
				count ++;
			}
		}
		gpdata.setgIsGjdNum(count);
	}
}